import subprocess
import datetime
import time
import os
import logging

cur_dir = os.path.dirname(os.path.abspath(__file__))
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s:%(message)s')

def fetch_news_internal(script,data_dir):
    today=datetime.datetime.now().strftime('%Y-%m-%d')
    data_path="{0}/{1}".format(data_dir,today)
    py_path="{0}/{1}".format(cur_dir,script)
    subprocess.call(['python3',py_path,],stdout=open(data_path,'w'))

def fetch_feng():
    logging.debug("Begin to fetch feng.")
    fetch_news_internal("fetch_feng.py",'/home/glx/news/feng')
    logging.debug("Finish fetching feng.")
    
def fetch_xinhua():
    logging.debug("Begin to fetch xinhua.")
    fetch_news_internal("fetch_xinhua.py",'/home/glx/news/xinhua')
    logging.debug("Finish fetching xinhua.")

def fetch_ce():
    logging.debug("Begin to fetch caijing.")
    fetch_news_internal("fetch_ce.py",'/home/glx/news/ce')
    logging.debug("Finish fetching caijing.")

fetched=False
while True:
    hour=datetime.datetime.now().strftime('%H')
    if hour=="21" and not fetched:
        logging.debug("Begin to fetch news.")
        fetch_feng()
        fetch_xinhua()
        fetch_ce()
        fetched=True

    if hour=="12" and fetched:
        logging.debug("Reset fetch status.")
        fetched=False

    time.sleep(600)
